package com.example.crm.config.shiro;

import com.example.crm.entity.Right;
import com.example.crm.entity.Role;
import com.example.crm.entity.User;
import com.example.crm.service.IRoleService;
import com.example.crm.service.IUserService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.cache.Cache;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;


import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * 安全数据源
 * @author lenovo
 */
public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private IUserService userService;
    @Resource
    private IRoleService roleService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    //redis中数据的key的前缀
    /**
     * 登录计数
     */
    private String SHIRO_LOGIN_COUNT = "shiro_login_count_";
    /**
     * 锁定用户登录
     */
    private String SHIRO_IS_LOCK = "shiro_is_lock";

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("调用MyShiroRealm.doGetAuthenticationInfo获取身份信息！");
        //获得身份信息
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String usrName = token.getUsername();
        //每次访问，登录次数加1
        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
        opsForValue.increment(SHIRO_LOGIN_COUNT + usrName, 1);
        //计数大于5时，设置用户被锁定一小时，清空登录计数
        if (Integer.parseInt(opsForValue.get(SHIRO_LOGIN_COUNT + usrName)) > 5) {
            opsForValue.set(SHIRO_IS_LOCK + usrName, "LOCK");
            stringRedisTemplate.expire(SHIRO_IS_LOCK + usrName, 1, TimeUnit.HOURS);
            //清空登录计数
            stringRedisTemplate.delete(SHIRO_LOGIN_COUNT + usrName);
        }
        if("LOCK".equals(opsForValue.get(SHIRO_IS_LOCK + usrName))){
            throw new DisabledAccountException();
        }
        User user = userService.getUserByUsrName(usrName);
        if (user == null) {
            //账号错误
            throw new UnknownAccountException();
        }
        if (user.getUsrFlag() == null || user.getUsrFlag().intValue() == 0) {
            //账号锁定
            throw new LockedAccountException();
        }
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(
                //身份(根据用户名查询数据库获得的用户)
                user,
                //凭证(查询数据库获得的密码)
                user.getUsrPassword(),
                //加密使用的salt
                ByteSource.Util.bytes("czkt"),
                // Realm对象的名称
                getName());
        //assertCredentialsMatch(token,info);
        //返回身份信息
        return info;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("调用MyShiroRealm.doGetAuthorizationInfo获取权限信息！");
        //获得权限信息
        User user = (User) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //静态授权：授予主体(用户)相应的角色和权限
        /*info.addRole(user.getRole().getRoleName());
        //所有用户拥有"用户列表"权限
        info.addStringPermission("用户列表");
        //管理员拥有"增删改"权限
        if("管理员".equals(user.getRole().getRoleName())){
            info.addStringPermission("用户添加");
            info.addStringPermission("用户编辑");
            info.addStringPermission("用户删除");
        }*/
        //动态授权
        //Role role = user.getRole();
        Role role = roleService.findRoleByUsers(user);
        if (role != null) {
            info.addRole(user.getRole().getRoleName());
            //Set<Right> rights = role.getRights();
            List<Right> rights = roleService.findRightsByRole(role);
            if (rights != null && rights.size() > 0) {
                for (Right right : rights) {
                    info.addStringPermission(right.getRightCode());
                }
            }
        }
        return info;
    }

    public void clearMyCachedAuthorizationInfo() {
        clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }

    public void clearAllCachedAuthorizationsInfo() {
        //权限缓存是否可用
        if(this.isAuthenticationCachingEnabled()){
            Cache<Object,AuthorizationInfo> cache = null;
            CacheManager cacheManager = this.getCacheManager();
            if(cacheManager != null){
                //获得权限缓存
                String cacheName = this.getAuthenticationCacheName();
                //获得权限缓存
                cache = cacheManager.getCache(cacheName);
            }
            if(cache != null){
                //清空
                cache.clear();
            }
        }
    }
}